package services

import (
	"errors"
	database "hft/Database"
	"hft/Database/admin"
	"hft/Http/Models/request"
	"hft/global"
)

type ShopRoute struct{}

func (*ShopRoute) CreateShopRoute(data *request.ShopRouteRes) (err error) {

	res := global.OC_DB.Where("route_name = ?", data.RouteName).FirstOrCreate(&admin.ShopRoute{
		Base:              database.Base{Sort: data.Sort},
		Name:              data.Name,
		RouteName:         data.RouteName,
		Path:              data.Path,
		Title:             data.Title,
		Description:       data.Description,
		Keywords:          data.Keywords,
		AppPath:           data.AppPath,
		ParamsDescription: data.ParamsDescription,
		Example:           data.Example,
	})

	if res.Error != nil {
		return errors.New("未知错误")
	}

	if res.RowsAffected == 0 {
		return errors.New("该路由已存在")
	}

	return nil
}

func (*ShopRoute) EditShopRoute(data *request.ShopRouteRes) (err error) {

	var route *admin.ShopRoute

	err = global.OC_DB.Model(&admin.ShopRoute{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"sort":               data.Sort,
		"app_path":           data.AppPath,
		"id":                 data.ID,
		"name":               data.Name,
		"route_name":         data.RouteName,
		"path":               data.Path,
		"title":              data.Title,
		"description":        data.Description,
		"keywords":           data.Keywords,
		"params_description": data.ParamsDescription,
		"example":            data.Example,
	}).Error

	if err != nil {
		return errors.New("该路由不存在")
	}

	global.OC_DB.First(&route, data.ID)

	return nil
}

func (*ShopRoute) GetShopRouteList(canJump int) (data []*admin.ShopRoute, err error) {

	var list []*admin.ShopRoute

	global.OC_DB.Order("sort desc").Find(&list)
	return list, nil

}

func (*ShopRoute) Delete(ids []int) (err error) {

	err = global.OC_DB.Unscoped().Delete(&admin.ShopRoute{}, ids).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

var ShopRouteService = new(ShopRoute)
